package com.jinyi.wwdeng.ui.steps.fragment

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.jinyi.base.utils.img.ImageUtil
import com.jinyi.base.utils.log.HHLog
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentStepOcrPassportBinding
import com.jinyi.wwdeng.network.ApiService
import com.jinyi.wwdeng.network.HttpBaseParams.addCommonParams
import com.jinyi.wwdeng.pro.ProFragment
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.steps.act.OcrCameraAct
import com.jinyi.wwdeng.ui.steps.act.OcrCropAct
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_CONTENT_TYPE
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_FILE_PATH
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_ORC_FRONT
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_ORC_TYPE
import com.jinyi.wwdeng.ui.steps.act.StepListAct
import com.jinyi.wwdeng.utils.dialog.PhotoDialog
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/19 18:22
 * @Annotation：流程- 证件照 - 护照信息
 */
class OcrPassportFragment: ProFragment() {

    lateinit var binding: FragmentStepOcrPassportBinding
    //广播接收器
    private var mRecevier: ImageUsedRecevier? = null
    //正面照
    private var imgFrontUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentStepOcrPassportBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        //注册广播，接收图片上传完成后的使用通知
        registerImgUseRecevier()

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        val intent = Intent(context, OcrCropAct::class.java)
                        val bundle = Bundle()
                        bundle.putInt(KEY_CONTENT_TYPE,2)//1相机  2相册
                        bundle.putString(KEY_FILE_PATH,localPath)
                        bundle.putInt(KEY_ORC_TYPE,2)//证件类型  1身份证  2护照  3驾驶证
                        bundle.putBoolean(KEY_ORC_FRONT,true)//是否是正面
                        intent.putExtras(bundle)
                        openCropResultLauncher.launch(intent)
                    }
                }

            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //护照
        binding.imgView.setOnClickListener {
            if (imgFrontUrl .isNotEmpty()){
                return@setOnClickListener
            }
            showPhotoDialog()
        }
        //下一步
        binding.btnNext.setOnClickListener {
            if (imgFrontUrl.isEmpty()){
                showToast(getString(R.string.submit_error))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.API_PATH_OCR_INFO)
                put("cardType","PASSPORT")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
            }
            val act = context as StepListAct
            act.onSubmitRequest(params)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_OCR_PASSPORT_NEXT,"")
        }
    }

    override fun initData() {
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(){
        val photoDialog = PhotoDialog(context,"Passport",object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CAMERA,"Passport")
                onOpenCamera()
            }
            override fun openAlbum() {
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_ALBUM,"Passport")
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
            }
        }
    }

    /**
     * 相册选择照片
     */
    private val openAlbumResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                val uri = result.data!!.data
                val imgPath = getRealPathFromURI(uri!!)
                HHLog.e("文件路径>>>>>>>>>>>>>>$imgPath")
                val intent = Intent(context, OcrCropAct::class.java)
                val bundle = Bundle()
                bundle.putInt(KEY_CONTENT_TYPE,2)//1相机  2相册
                bundle.putString(KEY_FILE_PATH,imgPath)
                bundle.putInt(KEY_ORC_TYPE,2)//证件类型  1身份证  2护照  3驾驶证
                bundle.putBoolean(KEY_ORC_FRONT,true)//是否是正面
                intent.putExtras(bundle)
                openCropResultLauncher.launch(intent)
//                onIntent(IdCardCropAct::class.java,bundle)
            }
        }
    }

    /**
     * 图片剪裁
     */
    private val openCropResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e("相册选择后剪裁返回，不需要操作")

            }
        }
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
//        val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
        val filePath = App.instance().filesDir.absolutePath
        val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
//        val intent = Intent(context, CameraActivity2::class.java)
        val intent = Intent(context, OcrCameraAct::class.java)
        intent.putExtra(OcrCameraAct.KEY_OUTPUT_FILE_PATH, outputFile.absolutePath)
        val bundle = Bundle()
        bundle.putInt(KEY_ORC_TYPE,2)//证件类型  1身份证  2护照  3驾驶证
        bundle.putBoolean(KEY_ORC_FRONT,true)//是否是正面
        intent.putExtras(bundle)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
//        val intent = Intent(Intent.ACTION_PICK)
//        intent.setType("image/*")
//        openAlbumResultLauncher.launch(intent)
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }

    /**
     * 注册图片使用广播
     */
    private fun registerImgUseRecevier() {
        mRecevier = ImageUsedRecevier(this)
        var intentFilter = IntentFilter()
        intentFilter.addAction(AppConfigs.Action.ACTION_UPLOAD_USE)//上传后使用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requireContext().registerReceiver(mRecevier, intentFilter, Context.RECEIVER_EXPORTED)
        } else {
            requireContext().registerReceiver(mRecevier, intentFilter)
        }
    }

    class ImageUsedRecevier(fragment: OcrPassportFragment) : BroadcastReceiver() {
        var fragment = fragment
        override fun onReceive(context: Context, intent: Intent) {
            fragment.onRecevierEvent(intent)
        }
    }

    /**
     * 处理广播接收事件处理
     */
    private fun onRecevierEvent(intent: Intent){
        //根据需求添加自己需要关闭页面的action
        when(intent.action){
            AppConfigs.Action.ACTION_UPLOAD_USE -> {//更新流程状态
                val data = JSONObject(intent.getStringExtra("imgData"))
                imgFrontUrl = data.optString("imgUrl")
                val imgPath = data.optString("imgPath")
                val isFront = data.optBoolean("isFront")
                ImageUtil.getInstance().loadImage(context,binding.imgView,imgPath)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(String.format(TrackEventType.PAGE.PAGE_STEP_OCR_XX_START,"Passport"),"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(String.format(TrackEventType.PAGE.PAGE_STEP_OCR_XX_END,"Passport"),"")
        if (mRecevier != null){
            requireContext().unregisterReceiver(mRecevier)
        }
    }
}